<template>
  <div style="display: flex">
    <div>
      <div>
        <input
          v-model="keywords"
          type="text"
          placeholder="请输入关键词"
          @input="onInput"
          style="width: 400px; padding: 5px; margin-right: 5px;"
        />
        <ul v-if="options.length > 0" style="list-style-type: none; padding: 0; margin: 0; border: 1px solid #ccc; max-height: 150px; overflow-y: auto;">
          <li
            v-for="item in options"
            :key="item.id"
            @click="selectOption(item)"
            style="padding: 5px; cursor: pointer; display: flex; justify-content: space-between; align-items: center;"
          >
            <span>{{ item.name }}</span>
            <span style="color: #8492a6; font-size: 13px;">{{ item.district }}</span>
          </li>
        </ul>
      </div>
      <div id="container" class="container"></div>
    </div>
    <div class="info-box">
      纬度：{{ form.lat }}
      <br />
      经度：{{ form.lng }}
      <p>详细地址：{{ form.address }}</p>
    </div>
  </div>
</template>

<script>
import AMapLoader from '@amap/amap-jsapi-loader';
import { getequipmentlist, getTitle } from '@/api/echarts';

let distCluster = null;
let pointSimplifierIns = null;

export default {
  name: 'TestIndex',
  data() {
    return {
      map: null,
      marker: null,
      geoCoder: null,
      AutoComplete: null,
      keywords: "",
      form: {
        lng: "",
        lat: "",
        address: "",
        adcode: "",
      },
      loading: false,
      options: [], // 确保 options 是一个数组
      lat: null,
      lng: null,
      zoom: 5, // 设置一个默认值
    };
  },
  mounted() {
    this.initMap(); // 在组件挂载时初始化地图
  },
  methods: {
    async fetchlnglat() {
      try {
        const title = await getTitle();
        this.lat = parseFloat(title.msg.lat);
        this.lng = parseFloat(title.msg.lng);
        this.zoom = title.msg.zoom;

        // 检查经纬度是否有效
        if (!isNaN(this.lat) && !isNaN(this.lng) && this.map) {
          this.map.setCenter([this.lng, this.lat]); // 使用从接口返回的经纬度设置地图中心点
          this.map.setZoom(this.zoom);
        } else {
          console.error('无效的经纬度:', this.lat, this.lng, this.zoom);
        }
      } catch (error) {
        console.error('Error fetching title:', error);
      }
    },

    initMap() {
      AMapLoader.load({
        key: "f8c954755588cd09132500151dc4d01c",
        version: "2.0",
        plugins: [
          "AMap.Scale", 
          "AMap.Marker", 
          "AMap.InfoWindow", 
          "AMap.MarkerCluster", 
          "AMap.Geocoder", 
          "AMap.AutoComplete"
        ],
        AMapUI: {
          version: '1.1',
          plugins: ['overlay/SimpleMarker']
        }
      }).then((AMap) => {
        this.map = new AMap.Map("container", {
          viewMode: "2D",
          zoom: this.zoom,
          center: [105.602725, 37.076636], // 使用默认中心点
          mapStyle: 'amap://styles/blue',
        });

        this.geoCoder = new AMap.Geocoder({
          city: "010",
          radius: 1000,
        });
        this.AutoComplete = new AMap.AutoComplete({ city: "全国" });

        this.map.on("click", (e) => {
          this.form.lng = e.lnglat.lng;
          this.form.lat = e.lnglat.lat;
          this.removeMarker();
          this.setMapMarker();
        });

        // 设置地图的边界，防止循环
        const bounds = new AMap.Bounds(
          new AMap.LngLat(73.502355, 3.837031),  // 西南角
          new AMap.LngLat(135.09567, 53.563624) // 东北角
        );
        this.map.setLimitBounds(bounds);

        this.aMapUiLoad(); // 确保地图 UI 组件加载
        this.fetchlnglat(); // 获取地图中心点
      }).catch((e) => {
        console.log(`高德地图加载错误提示${e}`);
      });
    },

    currentSelect(val) {
      if (!val || !val.location) {
        console.error('Invalid selection: val or val.location is undefined');
        return;
      }
      this.form = {
        lng: val.location.lng,
        lat: val.location.lat,
        address: `${val.district} ${val.address}`,
        adcode: val.adcode,
      };
      this.removeMarker();
      this.setMapMarker();
    },

    setMapMarker() {
      if (!this.map || !this.form.lng || !this.form.lat) return;

      this.map.setFitView();
      this.marker = new AMap.Marker({
        map: this.map,
        position: [this.form.lng, this.form.lat],
      });
      this.toGeoCoder();
      this.map.setFitView();
      this.map.add(this.marker);
    },

    removeMarker() {
      if (this.marker) {
        this.map.remove(this.marker);
        this.marker = null; // 确保 marker 被正确清除
      }
    },

    toGeoCoder() {
      const lnglat = [this.form.lng, this.form.lat];
      this.geoCoder.getAddress(lnglat, (status, result) => {
        if (status === 'complete' && result.regeocode) {
          this.form.address = result.regeocode.formattedAddress;
        }
      });
    },

    onInput() {
      if (this.keywords !== "") {
        this.loading = true;
        setTimeout(() => {
          this.loading = false;
          this.AutoComplete.search(this.keywords, (status, result) => {
            if (status === 'complete' && result.tips) {
              this.options = result.tips;
            } else {
              this.options = []; // 清空选项
            }
          });
        }, 200);
      } else {
        this.options = [];
      }
    },

    selectOption(val) {
      if (!val || !val.location) {
        console.error('Invalid selection: val or val.location is undefined');
        return;
      }
      this.form = {
        lng: val.location.lng,
        lat: val.location.lat,
        address: `${val.district} ${val.address}`,
        adcode: val.adcode,
      };
      this.options = [];
      this.removeMarker();
      this.setMapMarker();
    },

    aMapUiLoad() {
      AMapUI.loadUI(['misc/DistrictCluster', 'misc/PointSimplifier', 'misc/Utils'], (DistrictCluster, PointSimplifier, utils) => {
        function MyRender(distClusterIns, opts) {
          MyRender.__super__.constructor.apply(this, arguments);
        }

        utils.inherit(MyRender, DistrictCluster.Render.Default);

        utils.extend(MyRender.prototype, {
          drawFeaturePolygons: function (ctx, polygons, styleOptions, feature, dataItems) {
            MyRender.__super__.drawFeaturePolygons.apply(this, arguments);
            if (dataItems.length > 0) {
              this.drawMyLabel(feature, dataItems);
            }
          },
          _initContainter: function () {
            MyRender.__super__._initContainter.apply(this, arguments);
            this._createCanvas('mylabel', this._container);
          },
          drawMyLabel: function (feature, dataItems) {
            var pixelRatio = this.getPixelRatio();
            var containerPos = map.lngLatToContainer(feature.properties.centroid || feature.properties.center);
            var labelCtx = this._getCanvasCxt('mylabel');
            var centerX = containerPos.getX() * pixelRatio,
                centerY = containerPos.getY() * pixelRatio;

            var text = feature.properties.name + ' (' + dataItems.length + ')';
            labelCtx.font = 14 * pixelRatio + 'px 微软雅黑';
            var textMetrics = labelCtx.measureText(text);
            var halfTxtWidth = textMetrics.width / 2;

            // 计算背景矩形的尺寸
            var rectWidth = textMetrics.width + 12 * pixelRatio; // 增加内边距
            var rectHeight = 22 * pixelRatio;
            var rectX = centerX - halfTxtWidth - 6 * pixelRatio;
            var rectY = centerY - rectHeight / 2;
            var cornerRadius = 5 * pixelRatio;

            // 绘制圆角矩形背景
            labelCtx.save();
            labelCtx.beginPath();
            labelCtx.moveTo(rectX + cornerRadius, rectY);
            labelCtx.lineTo(rectX + rectWidth - cornerRadius, rectY);
            labelCtx.quadraticCurveTo(rectX + rectWidth, rectY, rectX + rectWidth, rectY + cornerRadius);
            labelCtx.lineTo(rectX + rectWidth, rectY + rectHeight - cornerRadius);
            labelCtx.quadraticCurveTo(rectX + rectWidth, rectY + rectHeight, rectX + rectWidth - cornerRadius, rectY + rectHeight);
            labelCtx.lineTo(rectX + cornerRadius, rectY + rectHeight);
            labelCtx.quadraticCurveTo(rectX, rectY + rectHeight, rectX, rectY + rectHeight - cornerRadius);
            labelCtx.lineTo(rectX, rectY + cornerRadius);
            labelCtx.quadraticCurveTo(rectX, rectY, rectX + cornerRadius, rectY);
            labelCtx.closePath();
            labelCtx.fillStyle = 'rgba(0,0,0,0.5)';
            labelCtx.fill();
            labelCtx.restore();

            // 绘制文本
            labelCtx.save();
            labelCtx.textAlign = 'center';
            labelCtx.textBaseline = 'middle';
            labelCtx.fillStyle = 'white';
            labelCtx.fillText(text, centerX, centerY);
            labelCtx.restore();
          }
        });

        distCluster = new DistrictCluster({
          map: this.map,
          getPosition: function (item) {
            return item.position;
          },
          renderConstructor: MyRender,
          renderOptions: {
            featureStyle: {
              fillStyle: 'rgba(102,170,0,0.5)',
              lineWidth: 2,
              strokeStyle: 'rgba(25, 66, 3, 0.57)',
              hoverOptions: {
                fillStyle: 'rgba(255,255,255,0.2)'
              }
            }
          }
        });

        pointSimplifierIns = new PointSimplifier({
          map: this.map,
          autoSetFitView: true,
          getPosition: function (item) {
            return item.position;
          },
          getHoverTitle: function (dataItem, idx) {
            return idx + ': ' + dataItem.name;
          },
          renderOptions: {
            pointStyle: {
              width: 8,
              height: 8,
              fillStyle: null,
              lineWidth: 1
            },
            topNAreaStyle: {
              '2': {
                width: 15,
                height: 15,
                fillStyle: '#5A5FF6'
              },
              '1': {
                width: 20,
                height: 20,
                fillStyle: '#F6E45A'
              },
              '0': {
                width: 25,
                height: 25,
                fillStyle: '#F35A5A'
              }
            },
            hoverTitleStyle: {
              position: 'top'
            },
            hoverPointStyle: {
              width: 22,
              height: 22
            }
          }
        });

        this.getPointSimplifierData();
      });
    },

    async getPointSimplifierData() {
      try {
        const res = await getequipmentlist();
        const validData = res.msg.filter(
          item => item.lat && item.lng && !isNaN(item.lat) && !isNaN(item.lng)
        );

        const data = validData.map(item => ({
          name: item.content,
          position: [parseFloat(item.lng), parseFloat(item.lat)],
        }));

        if (pointSimplifierIns) {
          pointSimplifierIns.setData(data);
        }

        if (distCluster) {
          distCluster.setData(data);
        }
      } catch (error) {
        console.error('获取设备列表数据时出错:', error);
      }
    }
  }
};
</script>

<style scoped>
.container {
  width: 800px;
  height: 700px;
}
.info-box {
  padding: 20px;
}
</style>
